package com.zy.mc_module.base;

import android.content.Context;
import android.content.Intent;
import android.content.res.Resources;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.RecyclerView;
import androidx.recyclerview.widget.RecyclerView.Adapter;
import android.view.View;
import android.view.inputmethod.InputMethodManager;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.hwangjr.rxbus.RxBus;
import com.kingja.loadsir.callback.Callback;
import com.kingja.loadsir.core.LoadService;
import com.kingja.loadsir.core.LoadSir;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnLoadMoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;
import com.zy.mc_module.R;
import com.zy.mc_module.mvp.base.IPresenter;
import com.zy.mc_module.mvp.base.IView;
import com.zy.mc_module.utils.AppTools;
import com.zy.mc_module.utils.StringsUtils;
import com.zy.mc_module.utils.loadsir.EmptyCallback;
import com.zy.mc_module.utils.loadsir.ErrorCallback;
import com.zy.mc_module.utils.loadsir.LoadingCallback;

import java.util.List;

import butterknife.ButterKnife;
import io.reactivex.subjects.PublishSubject;

/**
 * Created on 18/10/20
 * Activity基类
 */
public abstract class BaseActivity<V extends IView, P extends IPresenter<V>> extends AppCompatActivity {
    public String TAG = getClass().getSimpleName() + "";
    protected Context context = BaseActivity.this;
    protected PublishSubject<Object> publishSubject;
    protected P presenter;
    private LoadService loadService;
    //使用LoadSir
    private boolean isNeedLoadSir = false;
    //指定需要加载的视图
    private View loadView;

    protected int mDistance;

    //下拉刷新
    private SmartRefreshLayout refreshLayout;
    private RecyclerView recyclerView;

    /**
     * 分页加载
     **/
    protected int page = 1;//页数
    protected int size = 10;//每页数目

    /***
     * 布局Id
     */
    protected abstract int getLayoutId();

    @Override
    public void startActivity(Intent intent) {
        super.startActivity(intent);
        overridePendingTransition(R.anim.activity_in_from_right, R.anim.activity_out_from_left);
    }

    @Override
    public void startActivityForResult(Intent intent, int requestCode) {
        super.startActivityForResult(intent, requestCode);
        overridePendingTransition(R.anim.activity_in_from_right, R.anim.activity_out_from_left);
    }

    protected void onCreate(Bundle savedInstanceState) {
        // 8.0 Only fullscreen opaque activities can request orientation
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            setTheme(R.style.AppTheme8);
        }
        //修改底部导航栏颜色
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            getWindow().setNavigationBarColor(Color.parseColor("#fcfcfc"));
        }
        super.onCreate(savedInstanceState);
        setContentView(getLayoutId());
        //添加Activity
        App.getInstance().addActivity(this);
        //绑定ButterKnife
        ButterKnife.bind(this);
        //初始化P层
        presenter = createPresenter();
        if (null != presenter) {
            //绑定Activity
            presenter.attachView((V) this);
        }
        //是否使用RxBus
        if (isNeedRxBus()) {
            RxBus.get().register(this);
        }
        //注册loadsir
        initLoadsir();
        //初始化视图
        initView();
        initView(savedInstanceState);
        //初始化事件
        initListener();
    }

    /***
     * 注册LoadSir
     */
    private void initLoadsir() {
        //判断LoadSir
        isLoadSir();
        //是否使用LoadSir
        if (isNeedLoadSir) {
            //判断 是否指定了需要加载的视图
            loadService = LoadSir.getDefault().register(null == loadView ? this : loadView,
                    (Callback.OnReloadListener) v -> {
                        //重新加载逻辑
                        reloadData();
                    });
        }
    }

    /***
     * 创建Mvp Presenter实例
     */
    protected P createPresenter() {
        return null;
    }

    protected void initView() {

    }

    protected void initView(Bundle savedInstanceState) {

    }

    protected void initListener() {

    }

    /***
     * LoadSir的重新加载数据
     */
    protected void reloadData() {

    }

    /***
     * 是否使用LoadSir等一系列功能
     * arg[0]:使用LoadSir
     * arg[1]:指定需要加载的视图
     */
    protected void isLoadSir(Object... objects) {
        if (objects.length == 1) {
            //使用LoadSir,未指定加载视图
            isNeedLoadSir = (boolean) objects[0];
            loadView = null;
        } else if (objects.length == 2) {
            //使用LoadSir,并指定需要加载视图
            isNeedLoadSir = (boolean) objects[0];
            loadView = this.findViewById((Integer) objects[1]);
        }
    }

    /***
     * 是否使用RxBus,默认false
     */
    protected boolean isNeedRxBus() {
        return false;
    }

    /***
     * 封装下拉刷新/上拉加载逻辑
     */
    protected void initRefresh(SmartRefreshLayout refreshLayout, RecyclerView recyclerView) {
        this.recyclerView = recyclerView;
        this.refreshLayout = refreshLayout;

        //下拉刷新
        refreshLayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(RefreshLayout refreshlayout) {
                refreshlayout.setEnableLoadMore(true);
                page = 1;
                refreshData(true);
            }
        });
        //上拉加载
        refreshLayout.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore(RefreshLayout refreshlayout) {
                page++;
                refreshData(false);
            }
        });
    }

    /***
     * 刷新加载数据
     */
    protected void refreshData(boolean ReOrLo) {
    }

    /***
     * 刷新完成
     */
    protected void refreshComplete(Object object) {
        if (object instanceof List) {
            List list = (List) object;
            Adapter recyclerViewAdapter = recyclerView.getAdapter();
            if (null != recyclerViewAdapter) {
                if (recyclerViewAdapter instanceof BaseAdapter) {
                    BaseAdapter adapter = (BaseAdapter) recyclerView.getAdapter();
                    if (page == 1) {
                        adapter.setAll(list);
                        if (adapter.getList().size() > 0) {
                            recyclerView.scrollToPosition(0);
                        }
                    } else {
                        adapter.addAll(list);
                    }
                } else if (recyclerViewAdapter instanceof BaseQuickAdapter) {
                    BaseQuickAdapter adapter = (BaseQuickAdapter) recyclerView.getAdapter();
                    if (page == 1) {
                        adapter.setNewData(list);
                        if (adapter.getData().size() > 0) {
                            recyclerView.scrollToPosition(0);
                        }
                    } else {
                        adapter.addData(list);
                    }
                }
            }
            if (StringsUtils.isEmpty(list) && page > 1) {
                page--;
                refreshLayout.setEnableLoadMore(false);
            }
        } else if (object instanceof Boolean) {
            boolean b = (boolean) object;
            if (b && page > 1) {
                page--;
            }
        }
        AppTools.finishRefresh(refreshLayout);
    }

    //--------------------------------LoadSir的反馈页-----------------------------------

    /***
     * 显示加载页
     */
    public void showLoading() {
        loadService.showCallback(LoadingCallback.class);
    }

    /***
     * 关闭加载页
     */
    public void disLoading() {
        loadService.showSuccess();
    }

    public void disLoading(long time) {
        new Handler().postDelayed(() -> loadService.showSuccess(), time);
    }

    /***
     * 暂无数据页
     */
    public void showEmpty() {
        loadService.showCallback(EmptyCallback.class);
    }

    public void showEmpty(Class<? extends Callback> callback) {
        loadService.showCallback(callback);
    }

    public void showEmpty(List list) {
        if (null == list || list.size() <= 0) {
            loadService.showCallback(EmptyCallback.class);
        } else {
            disLoading();
        }
    }

    public void showEmpty(List list, Class<? extends Callback> callback) {
        if (null == list || list.size() <= 0) {
            loadService.showCallback(callback);
        } else {
            disLoading();
        }
    }

    /***
     * 请求错误页
     */
    public void showError() {
        loadService.showCallback(ErrorCallback.class);
    }

    public void showError(List list) {
        if (null == list || list.size() <= 0) {
            loadService.showCallback(ErrorCallback.class);
        } else {
            disLoading();
        }
    }
    //----------------------------------------

    @Override
    public Resources getResources() {
//        //字体不随系统字体变化
//        Resources resources = super.getResources();
//        Configuration newConfig = resources.getConfiguration();
//        DisplayMetrics displayMetrics = resources.getDisplayMetrics();
//
//        if (resources != null && newConfig.fontScale != 1) {
//            newConfig.fontScale = 1;
//            if (Build.VERSION.SDK_INT >= 17) {
//                Context configurationContext = createConfigurationContext(newConfig);
//                resources = configurationContext.getResources();
//                displayMetrics.scaledDensity = displayMetrics.density * newConfig.fontScale;
//            } else {
//                resources.updateConfiguration(newConfig, displayMetrics);
//            }
//        }
        //屏幕适配
        //AutoSizeCompat.autoConvertDensityOfGlobal(super.getResources());

        return super.getResources();
    }

    /**
     * 隐藏键盘
     */
    protected void hideInput() {
        //et_con.setFocusable(false);
        InputMethodManager imm = (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE);
        View v = getWindow().peekDecorView();
        if (null != v) {
            imm.hideSoftInputFromWindow(v.getWindowToken(), 0);
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (isNeedRxBus()) {
            //注销RxBus
            RxBus.get().unregister(this);
        }
        if (null != presenter) {
            presenter.detachView();
            presenter = null;
        }
        //取消订阅
        //SubscriptionManager.getInstance().cancelall();
        App.getInstance().removeActivity(this);
        App.getInstance().removeTmpActivity(this);
        //----
        //ShareUtil.recycle();
        //FixMemLeak.fixLeak(context);
    }

    @Override
    public void finish() {
        super.finish();
        overridePendingTransition(R.anim.activity_in_from_left, R.anim.activity_out_from_right);
    }

    /**
     * -----------------------解决微信分享成功后,留在微信不回调分享成功的问题start-------------------------------------------
     */
    public boolean isSharing;  //是否调起了分享。如果调起分享，这个值为true。
    private boolean isResume;  //Activity是否处于前台。

    @Override
    protected void onResume() {
        super.onResume();
        isSharing = false;
        isResume = true;
    }

    @Override
    protected void onPause() {
        super.onPause();
        isResume = false;
    }

    /** -----------------------解决微信分享成功后,留在微信不回调分享成功的问题end-------------------------------------------*/
}
